package com.jianshuge.app.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.R;
import com.jianshuge.app.adapter.ListViewBooklistAdapter;

import com.jianshuge.app.bean.Notice;
import com.jianshuge.app.bean.MyResult;
import com.jianshuge.app.bean.Booklist;
import com.jianshuge.app.bean.BooklistList;

import com.jianshuge.app.common.UIHelper;
import com.jianshuge.app.widget.PullToRefreshListView;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class UserBooklist extends BaseActivity {

	private ImageView mBack;
	private TextView mHeaderTitle;
	private ProgressBar mProgressbar;
	private Button booklist_catalog_fbl;
	private Button booklist_catalog_cbl;
	private Button booklist_catalog_pbl;
	
	private PullToRefreshListView mlvUserBooklist;
	private ListViewBooklistAdapter lvUserBooklistAdapter;
	private List<Booklist> lvUserBooklistData = new ArrayList<Booklist>();
	private View lvUserBooklist_footer;
	private TextView lvUserBooklist_foot_more;
	private ProgressBar lvUserBooklist_foot_progress;
    private Handler mUserBooklistHandler;
    private int lvSumData;
    
	private int curBooklistCatalog;
	private int curLvDataState;
	private int cur_visited_uid;
    
	private final static int DATA_LOAD_ING = 0x001;
	private final static int DATA_LOAD_COMPLETE = 0x002;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_booklist);
        
        this.initView();    
        this.initData();
	}
	
    /**
     * 头部按钮展示
     * @param type
     */
    private void headButtonSwitch(int type) {
    	switch (type) {
    	case DATA_LOAD_ING:
			mProgressbar.setVisibility(View.VISIBLE);
			break;
		case DATA_LOAD_COMPLETE:
			mProgressbar.setVisibility(View.GONE);
			break;
		}
    }
	
	//初始化视图控件
    private void initView()
    {
      	cur_visited_uid = getIntent().getIntExtra("cur_visited_uid", 0);
    	int cur_catalog = getIntent().getIntExtra("catalog", 3);
    	String header_title = getIntent().getStringExtra("header_title");
    	
    	
    	mHeaderTitle = (TextView)findViewById(R.id.user_booklist_head_title);
    	mHeaderTitle.setText(header_title);
    	
    	mBack = (ImageView)findViewById(R.id.favorite_head_back);
    	mBack.setOnClickListener(UIHelper.finish(this));
    	mProgressbar = (ProgressBar)findViewById(R.id.favorite_head_progress);
    	
    	booklist_catalog_fbl = (Button)findViewById(R.id.btn_booklist_catalog_fbl);
    	booklist_catalog_cbl = (Button)findViewById(R.id.btn_booklist_catalog_cbl);
    	booklist_catalog_pbl = (Button)findViewById(R.id.btn_booklist_catalog_pbl);
    	
    	booklist_catalog_fbl.setOnClickListener(favoriteBtnClick(booklist_catalog_fbl, BooklistList.CATALOG_FOLLOWED_BOOKLIST));
    	booklist_catalog_cbl.setOnClickListener(favoriteBtnClick(booklist_catalog_cbl, BooklistList.CATALOG_CREATED_BOOKLIST));
    	booklist_catalog_pbl.setOnClickListener(favoriteBtnClick(booklist_catalog_pbl, BooklistList.CATALOG_PART_BOOKLIST));
    	
    	
    	if( cur_catalog == BooklistList.CATALOG_FOLLOWED_BOOKLIST ) {
        	booklist_catalog_fbl.setEnabled(false);
        	curBooklistCatalog = BooklistList.CATALOG_FOLLOWED_BOOKLIST;
    	}
    	else if( cur_catalog == BooklistList.CATALOG_CREATED_BOOKLIST ) {
    		booklist_catalog_cbl.setEnabled(false);
        	curBooklistCatalog = BooklistList.CATALOG_CREATED_BOOKLIST;
    	}
    	else {
    		booklist_catalog_pbl.setEnabled(false);
        	curBooklistCatalog = BooklistList.CATALOG_PART_BOOKLIST;
    	}
    	
    	lvUserBooklist_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvUserBooklist_foot_more = (TextView)lvUserBooklist_footer.findViewById(R.id.listview_foot_more);
    	lvUserBooklist_foot_progress = (ProgressBar)lvUserBooklist_footer.findViewById(R.id.listview_foot_progress);

    	lvUserBooklistAdapter = new ListViewBooklistAdapter(this,  BooklistList.CATALOG_FOLLOWED_BOOKLIST, lvUserBooklistData, R.layout.booklist_listitem); 
    	mlvUserBooklist = (PullToRefreshListView)findViewById(R.id.user_booklist_listview);
    	
    	mlvUserBooklist.addFooterView(lvUserBooklist_footer);//添加底部视图  必须在setAdapter前
    	mlvUserBooklist.setAdapter(lvUserBooklistAdapter); 
    	
    	mlvUserBooklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		//点击头部、底部栏无效
        		if(position == 0 || view == lvUserBooklist_footer) return;
        		
        		Booklist booklist = null;
        		//判断是否是TextView
        		
        		if (view instanceof TextView) {
					booklist = (Booklist) view.getTag();
				} else {
					TextView tv = (TextView) view.findViewById(R.id.booklist_listitem_title);
					booklist = (Booklist) tv.getTag();
				}
				if (booklist == null)
					return;

				// 跳转书单详情页
				UIHelper.showBooklistDetail(view.getContext(), booklist.getId());
        	}
		});
    	
    	mlvUserBooklist.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				mlvUserBooklist.onScrollStateChanged(view, scrollState);
				
				//数据为空--不用继续下面代码了
				if(lvUserBooklistData.size() == 0) return;
				
				//判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if(view.getPositionForView(lvUserBooklist_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				if(scrollEnd && curLvDataState==UIHelper.LISTVIEW_DATA_MORE)
				{
					mlvUserBooklist.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					lvUserBooklist_foot_more.setText(R.string.load_ing);
					lvUserBooklist_foot_progress.setVisibility(View.VISIBLE);
					//当前pageIndex
					int pageIndex = lvSumData/20;
					loadLvUserBooklistData(cur_visited_uid, curBooklistCatalog, pageIndex, mUserBooklistHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}
			
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				mlvUserBooklist.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
			
		});
    	
    	mlvUserBooklist.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				//点击头部、底部栏无效
        		if(position == 0 || view == lvUserBooklist_footer) return false;				
				
        		Booklist _booklist = null;
        		//判断是否是TextView
        		if(view instanceof TextView){
        			_booklist = (Booklist)view.getTag();
        		}else{
        			TextView title = (TextView)view.findViewById(R.id.booklist_listitem_title);
        			_booklist = (Booklist)title.getTag();
        		} 
        		if(_booklist == null) return false;
        		
        		final Booklist booklist = _booklist;
        		
        		final AppContext ac = (AppContext)getApplication();
				//操作--删除
        		final int uid = ac.getLoginUid();

        		final Handler handler = new Handler(){
					public void handleMessage(Message msg) {
						if(msg.what == 1){
							MyResult res = (MyResult)msg.obj;
							if(res.OK()){
								lvUserBooklistData.remove(booklist);
								lvUserBooklistAdapter.notifyDataSetChanged();
							}
							UIHelper.ToastMessage(UserBooklist.this, res.getErrorMessage());
						}else{
							((AppException)msg.obj).makeToast(UserBooklist.this);
						}
					}        			
        		};
        		final Thread thread = new Thread(){
					public void run() {
						Message msg = new Message();
						/***
						try {
							Result res = ac.delFavorite(uid, fav.objid, fav.type);
							msg.what = 1;
							msg.obj = res;
			            } catch (AppException e) {
			            	e.printStackTrace();
			            	msg.what = -1;
			            	msg.obj = e;
			            }
			            ***/
			            
		                handler.sendMessage(msg);
					}        			
        		};
        		UIHelper.showFavoriteOptionDialog(UserBooklist.this, thread);
			
				return true;
			}        	
		});
		
    	
    	mlvUserBooklist.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
			public void onRefresh() {
				loadLvUserBooklistData(cur_visited_uid, curBooklistCatalog, 0, mUserBooklistHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
            }
        });
        
    }
    
    //初始化控件数据
  	private void initData()
  	{			
  		mUserBooklistHandler = new Handler()
		{
			public void handleMessage(Message msg) {
				
				headButtonSwitch(DATA_LOAD_COMPLETE);

				if(msg.what >= 0){						
					BooklistList list = (BooklistList)msg.obj;
					Notice notice = list.getNotice();

					switch (msg.arg1) {
					case UIHelper.LISTVIEW_ACTION_INIT:
					case UIHelper.LISTVIEW_ACTION_REFRESH:
					case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
						lvSumData = msg.what;
						lvUserBooklistData.clear();//先清除原有数据
						lvUserBooklistData.addAll(list.getBooklistList());
						break;
					case UIHelper.LISTVIEW_ACTION_SCROLL:
						lvSumData += msg.what;
						if(lvUserBooklistData.size() > 0){
							for(Booklist booklist1 : list.getBooklistList()){
								boolean b = false;
								for(Booklist booklist2 : lvUserBooklistData){
									if (booklist1.getId() == booklist2.getId()) {
										b = true;
										break;
									}
								}
								if(!b) lvUserBooklistData.add(booklist1);
							}
						}else{
							lvUserBooklistData.addAll(list.getBooklistList());
						}
						break;
					}	
					
					if(msg.what < 10){
						curLvDataState = UIHelper.LISTVIEW_DATA_FULL;
						lvUserBooklistAdapter.notifyDataSetChanged();
						lvUserBooklist_foot_more.setText(R.string.load_full);
					}else if(msg.what == 10){					
						curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
						lvUserBooklistAdapter.notifyDataSetChanged();
						lvUserBooklist_foot_more.setText(R.string.load_more);
					}
					
					//发送通知广播
					if(notice != null){
					//	UIHelper.sendBroadCast(UserBooklist.this, notice);
					}
				}
				else if(msg.what == -1){
					//有异常--显示加载出错 & 弹出错误消息
					curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
					lvUserBooklist_foot_more.setText(R.string.load_error);
					((AppException)msg.obj).makeToast(UserBooklist.this);
				}
				if(lvUserBooklistData.size()==0){
					curLvDataState = UIHelper.LISTVIEW_DATA_EMPTY;
					lvUserBooklist_foot_more.setText(R.string.load_empty);
				}
				
				lvUserBooklist_foot_progress.setVisibility(View.GONE);
				if(msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH){
					mlvUserBooklist.onRefreshComplete(getString(R.string.pull_to_refresh_update) + new Date().toLocaleString());
					mlvUserBooklist.setSelection(0);
				}else if(msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG){
					mlvUserBooklist.onRefreshComplete();
					mlvUserBooklist.setSelection(0);
				}
			}
		};
		
		this.loadLvUserBooklistData(cur_visited_uid, curBooklistCatalog, 0, mUserBooklistHandler,UIHelper.LISTVIEW_ACTION_INIT);
  	}
  	
    /**
     * 线程加载用户书单数据
     * @param catalog  3:关注的书单  4:创建的书单  5:参与的书单
     * @param pageIndex 当前页数
     * @param handler 处理器
     * @param action 动作标识
     */
	private void loadLvUserBooklistData(final int uid, final int catalog, final int pageIndex,final Handler handler,final int action){  
		headButtonSwitch(DATA_LOAD_ING);

		new Thread() {
			public void run() {
				Message msg = new Message();
				
				boolean isRefresh = false;
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				
				try {
					AppContext appContext = (AppContext) getApplication();
					BooklistList list = appContext.getBooklistList(catalog, pageIndex, uid, isRefresh);
					msg.what = list.getPageSize();
					msg.obj = list;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;
				msg.arg2 = UIHelper.LISTVIEW_DATATYPE_MYBOOKLIST;
				if (curBooklistCatalog == catalog)
					handler.sendMessage(msg);
			}
		}.start();
	} 
	
	private View.OnClickListener favoriteBtnClick(final Button btn,final int catalog){
    	return new View.OnClickListener() {
			public void onClick(View v) {
		    	if(btn == booklist_catalog_fbl)
		    		booklist_catalog_fbl.setEnabled(false);
		    	else
		    		booklist_catalog_fbl.setEnabled(true);
		    	
		    	if(btn == booklist_catalog_cbl)
		    		booklist_catalog_cbl.setEnabled(false);
		    	else
		    		booklist_catalog_cbl.setEnabled(true);
		    	
		    	if(btn == booklist_catalog_pbl)
		    		booklist_catalog_pbl.setEnabled(false);
		    	else
		    		booklist_catalog_pbl.setEnabled(true);

				lvUserBooklist_foot_more.setText(R.string.load_more);
				lvUserBooklist_foot_progress.setVisibility(View.GONE);
			
				curBooklistCatalog = catalog;
				loadLvUserBooklistData(cur_visited_uid, curBooklistCatalog, 0, mUserBooklistHandler, UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);		    		
			}
		};
    }
}
